package controllers

import dao._
import implicits.Implicits._
import play.api.cache.AsyncCacheApi
import play.api.libs.json.Json
import play.api.mvc._
import tool.FormTool
import tool.Pojo.DetailInfo
import utils.Utils

import javax.inject.Inject
import scala.concurrent.ExecutionContext.Implicits.global
import upickle.default._

/**
 * Created by yz on 16/9/2021
 */
class Basic344Controller @Inject()(cc: ControllerComponents, cache: AsyncCacheApi)(
  implicit val basicDao: Basic344Dao,
) extends AbstractController(cc) {

  def allByServer = Action.async { implicit request =>
    val map=request.body.asJson.get.toJsObject.value
    val pageData = FormTool.pageForm.bindFromRequest().get
    basicDao.selectAll(map,pageData).map { case (size, x) =>
      val array = Utils.getJsonByTs(x)
      Ok(Json.obj("rows" -> array, "total" -> size))
    }
  }

  def select2Values = Action.async { implicit request =>
    val data = FormTool.keysForm.bindFromRequest().get
    basicDao.selectUniqueValues(data.keys).map { valuess =>
      val vMap = data.keys.zip(valuess).toSeqMap
      Ok(Json.toJson(vMap))
    }
  }

  def browse = Action { implicit request =>
    Ok(views.html.basic344.browse())
  }

  def search = Action { implicit request =>
    Ok(views.html.basic344.search(None))
  }

  def searchByGeneId = Action.async { implicit request =>
    val data = FormTool.geneIdForm.bindFromRequest.get
    val geneIds = data.geneId.split(",").distinct
    basicDao.selectByGeneIds(geneIds).map { x =>
      val array = Utils.getArrayByTs(x)
      Ok(Json.toJson(array))
    }
  }

  def searchByRegion = Action.async { implicit request =>
    val data = FormTool.regionForm.bindFromRequest.get
    basicDao.selectByRegionData(data).map { x =>
      val array = Utils.getArrayByTs(x)
      Ok(Json.toJson(array))
    }
  }

  def allGeneIds = Action.async {
    basicDao.selectAllGeneIds.map { x =>
      Ok(Json.toJson(x))
    }
  }

  def allChrs = Action.async { implicit request =>
    basicDao.selectAllChrs.map { x =>
      Ok(Json.toJson(x))
    }
  }

  def detailInfo = Action.async { implicit request =>
    val queryMap = request.queryString.map { case (k, v) =>
      (k, v.head)
    }
    val data = writeJs(queryMap).transform(reader[DetailInfo.Request])
    basicDao.selectTByGeneId(data.geneId).map { x =>
      Ok(views.html.basic344.detailInfo(x,data.h2))
    }
  }

  def basicInfo = Action.async { implicit request =>
    val data = FormTool.geneIdForm.bindFromRequest().get
    basicDao.selectBasicByGeneId(data.geneId).map { x =>
      val array = Utils.getMapByT(x)
      Ok(Json.toJson(array))
    }
  }









}
